package org.vaadin.nf4v.core.handler.impl;

import com.vaadin.ui.Window;
import org.vaadin.nf4v.core.NavigableApplication;
import org.vaadin.nf4v.core.handler.InvalidUriHandler;
import org.vaadin.nf4v.core.navigation.InvalidUriException;
import org.vaadin.nf4v.core.navigation.NavigationManager;

/**
 * Default InvalidUriHandler implementation.
 * Shows error notification if current page is not empty (not first navigation).
 * Error message may be provided through constructor.
 *
 * If no current page, user will be redirected to home page.
 */
public class DefaultInvalidUriHandler implements InvalidUriHandler {
    private String error = "Invalid page";

    public DefaultInvalidUriHandler() {
    }

    public DefaultInvalidUriHandler(String error) {
        this.error = error;
    }

    @Override
    public void handleInvalidUri(String fragment, InvalidUriException ex) {
        if (NavigableApplication.getCurrentNavigableWindow().getNavigator().getCurrentPage() != null) {
            // if not first window page just show error
            ((Window)NavigableApplication.getCurrentNavigableWindow()).showNotification(error);
        } else {
            // if no other page was shown for this window - go to home page
            NavigationManager.navigateTo().home().go();
        }
    }
}
